<template>
    <div class="mdEditor">
        <v-md-editor
                v-model="text"
                height="600px" 
                @upload-image="handleUploadImage"
                :disabled-menus="[]">
        </v-md-editor>

        <el-button type="primary" @click="save">保存</el-button>
    </div>
</template>

<script>
    import {ossSign,ossUpload,ossMDUpload } from '../api/oss/index'
    export default {
        data() {
            return {
                text:""
            }
        },
        mounted() {

        },
        methods: {
            handleUploadImage(event, insertImage, files){
                console.log(files);
                ossSign({}).then((res)=>{
                    if(res.code == 200){
                        let ossInfo = res.data;
                        let fileName =  files[0].name;
                        let suffix = fileName.substr(fileName.lastIndexOf('.'))
                        ossUpload(files[0],ossInfo).then((res)=>{
                            let url= `${ossInfo.host}/${ossInfo.startsWith}${ossInfo.key}${suffix}`
                            insertImage({
                                url:url,
                                desc: fileName,
                                // width: 'auto',
                                // height: 'auto',
                            });
                        })
                    }
                })
            },
            save(){
                let that = this;
                let mdFile = new Blob([this.text],{ "type" : "text/plain;charset=utf-8" }); //利用Blob对象生成文件
                //获取参数
                ossSign({}).then((res)=>{
                    if(res.code == 200){
                        let ossInfo = res.data;
                        let fileName =  that.title+".md";
                        let suffix = ".md";
                        //进行上传
                        ossMDUpload(mdFile,fileName,ossInfo).then((res)=>{
                            if(res.status == 200){
                                let url= `${ossInfo.host}/${ossInfo.startsWith}${ossInfo.key}${suffix}`
                                console.log("md文件路径:"+url);
                                //todo 将url传给后端,后端再进行入库操作
                                
                            }else{
                                that.$message.error("文件上传错误")
                            }

                        })
                    }
                })
            }
        },
        components: {}
    }
</script>

<style lang="scss">
    .mdEditor {
    }
</style>